﻿<template>
  <my-container v-loading="pageLoading">
    <!--顶部操作-->
    <template #header>
      <el-form class="ad-form-query" :inline="true" @submit.native.prevent>
        <el-form-item>
          <my-search :fields="fields" @click="onSearch" />
        </el-form-item>
        <el-form-item v-if="checkPermission(['api:admin:carrieroperator:add'])">
          <el-button type="success" @click="onGetImportTemplate">下载模板</el-button>
        </el-form-item>
        <el-form-item v-if="checkPermission(['api:admin:carrieroperator:add'])">
          <el-button type="primary" @click="onAdd">批量导入</el-button>
        </el-form-item>
      </el-form>
    </template>

    <!--列表-->
    <el-table v-loading="listLoading" :data="pageList" highlight-current-row height="'100%'"
      style="width: 100%;height:100%;" @selection-change="onSelsChange">
           
      <el-table-column type="selection" width="50" />

      <el-table-column prop="id" label="导入批次Id" />

      <el-table-column prop="carrierOperatorName" label="运营商" />

      <el-table-column prop="carrierOperatorDictionaryName" label="套餐系列" />
           
      <el-table-column prop="networkCardDictionaryName" label="网卡类型" />
           
      <el-table-column prop="importSumCount" label="导入总卡数" />
           
      <el-table-column prop="importSuccessCount" label="导入成功卡数" />

      <el-table-column prop="importFailCount" label="导入失败卡数" />

      <el-table-column prop="Remark" label="失败原因" />

      <el-table-column prop="creationTime" label="创建时间" :formatter="formatCreatedTime" />
    </el-table>

    <!--分页-->
    <template #footer>
      <my-pagination ref="pager" :total="total" :checked-count="sels.length" @get-page="pageList" />
    </template>
    <!-- 添加 -->
    <my-window v-if="checkPermission(['api:admin:carrieroperator:add'])" title="添加" :visible.sync="addDialogFormVisible"
      @close="closeAddForm">
      <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-width="120px" :inline="false">
        <el-form-item label="选择excel文件" prop="file">
          <el-upload class="upload-demo" ref="upload" drag :action="uploadUrl" :headers="token"
            :on-success="onAvatarSuccess" :limit="1" :on-error="onAvatarError">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传excel文件，且不超过25M</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="运营商" prop="carrierOperatorId">
          <el-select v-model="addForm.carrierOperatorId" placeholder="请选择运营商" style="width: 100%">
            <el-option v-for="item in carrierOperatorList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="套餐系列" prop="carrierOperatorPackageDictionaryId">
          <el-select v-model="addForm.carrierOperatorPackageDictionaryId" placeholder="请选择套餐系列" style="width: 100%">
            <el-option v-for="item in carrierOperatorPackageDictionaryList" :key="item.id" :label="item.name"
              :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="卡类型" prop="networkCardDictionaryId">
          <el-select v-model="addForm.networkCardDictionaryId" placeholder="请选择卡类型" style="width: 100%">
            <el-option v-for="item in networkCardDictionaryList " :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="轮询网卡" prop="isPollingCard">
          <el-select v-model="addForm.isPollingCard" placeholder="请选择轮询网卡" style="width: 100%">
            <el-option v-for="item in pollingCardList" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click.native="addDialogFormVisible = false">取消</el-button>
        <my-confirm-button type="submit" :validate="addFormvalidate" :loading="addLoading" @click="onAddSubmit" />
      </template>
    </my-window>

  </my-container>
</template>

<script>
import { formatTime, listToTree, getTreeParents } from '@/utils'
import { getPageList, get, add, update, softDelete, batchSoftDelete, onGetImportTemplate } from '@/api/iot/import-network-card'
import { getCarrierOperatorList } from '@/api/iot/carrier-operator'
import { getCodeList } from "@/api/admin/dictionary-type";
import MyContainer from '@/components/my-container'
import MyConfirmButton from '@/components/my-confirm-button'
import MySearch from '@/components/my-search'
import MySearchWindow from '@/components/my-search-window'
import MyWindow from '@/components/my-window'

export default {
  name: 'importnetworkcard',
  components: { MyContainer, MyConfirmButton, MySearch, MySearchWindow, MyWindow },
  data() {
    return {
      // 高级查询字段
      fields: [
        { value: "id", label: "批次Id", default: true }
      ],
      dynamicFilter: null,
      pageList: [],
      carrierOperatorList: [],
      carrierOperatorPackageDictionaryList: [],
      networkCardDictionaryList: [],
      pollingCardList: [{
        name: "是",
        value: true
      }, {
        name: "否",
        value: false
      }],
      total: 0,
      sels: [], // 列表选中列
      addLoading: false,
      // 添加界面
      addDialogFormVisible: false,
      listLoading: false,
      pageLoading: false,
      addFormRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        account: [{ required: true, message: '请输入账户', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        secretKey: [{ required: true, message: '请输入密钥', trigger: 'blur' }],
        dictionaryId: [{ required: true, message: '请输入所属类别字典Id', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        shutdownThreshold: [{ required: true, message: '请输入停机阈值(MB)', trigger: 'blur' }],
        isDisable: [{ required: true, message: '请输入禁用', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
      },
      // 添加界面数据
      addForm: {
        file: "",
        carrierOperatorId: "",
        carrierOperatorPackageDictionaryId: "",
        networkCardDictionaryId: "",
        isPollingCard: true
      },
    }
  },
  async mounted() {
    await this.onGetPageList()
    await this.onGetCodeList();
    await this.onGetCarrierOperatorList();
  },
  computed: {
    // 上传图片路径
    uploadUrl() {
      return process.env.VUE_APP_BASE_IOT_API + "/iot/ImportNetworkCard/upload-excel";
    },
    // 请求令牌
    token() {
      return { Authorization: "Bearer " + this.$store.getters.token };
    },
  },
  methods: {
    formatCreatedTime(row, column, time) {
      return formatTime(time, 'YYYY-MM-DD HH:mm')
    },
    // 显示添加界面
    onAdd() {
      this.addDialogFormVisible = true;
    },
    async onGetImportTemplate() {
      const res = await onGetImportTemplate();
      if (!res?.success) {
        return
      }
      window.open(res.data)
    },
    // 关闭添加
    closeAddForm() {
      this.$refs.addForm.resetFields();
      this.addDialogFormVisible = false;
    },
    // 添加验证
    addFormvalidate() {
      let isValid = false;
      this.$refs.addForm.validate((valid) => {
        isValid = valid;
      });
      return isValid;
    },
    // 添加
    async onAddSubmit() {
      this.addLoading = true;
      const para = _.cloneDeep(this.addForm);
      const res = await add(para);
      this.addLoading = false;

      if (!res?.success) {
        return;
      }
      this.$message({
        message: this.$t("admin.addOk"),
        type: "success",
      });
      this.$refs["addForm"].resetFields();
      this.addDialogFormVisible = false;
      this.onGetPageList();
    },
    // 上传成功
    onAvatarSuccess(res) {
      if (!res?.code) {
        this.$refs.upload.clearFiles();
        if (res.msg) {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
        return;
      }
      this.addForm.file = res.data;
    },
    // 上传失败
    onAvatarError(err, file) {
      const res = err.message ? JSON.parse(err.message) : {};
      if (!res?.code) {
        this.$refs.upload.clearFiles();
        if (res.msg) {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      }
    },
    // 根据Code获取字典
    async onGetCodeList() {
      const res = await getCodeList({ code: "CarrierOperatorPackageDictionaryCode" });
      if (!res?.success) {
        return;
      }
      this.carrierOperatorPackageDictionaryList = res.data;

      const networkCardDictionaryRes = await getCodeList({ code: "NetworkCardDictionaryCode" });
      if (!networkCardDictionaryRes?.success) {
        return;
      }
      this.networkCardDictionaryList = networkCardDictionaryRes.data;
    },
    // 查询
    onSearch(dynamicFilter) {
      this.$refs.pager.setPage(1)
      this.dynamicFilter = dynamicFilter
      this.onGetPageList()
    },
    // 选择
    onSelsChange(sels) {
      this.sels = sels
    },
    // 获取运营商列表
    async onGetCarrierOperatorList() {
      const res = await getCarrierOperatorList();
      if (!res?.success) {
        return
      }
      this.carrierOperatorList = res.data;
    },
    // 获取列表
    async onGetPageList() {
      var pager = this.$refs.pager.getPager()
      const params = {
        ...pager,
        dynamicFilter: this.dynamicFilter
      }
      this.listLoading = true
      const res = await getPageList(params)
      this.listLoading = false
      if (!res?.success) {
        return
      }
      this.total = res.data.total
      const data = res.data.list
      data.forEach(d => {
        d._loading = false
      })
      this.pageList = data
    }
  }
}
</script>

<style lang="scss" scoped>
.my-search ::v-deep .el-input-group__prepend {
  background-color: #fff;
}
</style>
